package com.example.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class RateManager {

    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private DBHelper dbHelper;
    private Context context;

    public RateManager(Context context) {
        this.context = context;
        dbHelper = new DBHelper(context);
    }

    public List<ExchangeRateItem> getExchangeRates() {
        if (!isUpdatedToday()) {
            List<ExchangeRateItem> rates = fetchExchangeRatesFromNetwork();
            saveRatesToDatabase(rates);
            return rates;
        } else {
            return getExchangeRatesFromDatabase();
        }
    }

    private boolean isUpdatedToday() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String query = "SELECT update_date FROM exchange_rates ORDER BY id DESC LIMIT 1";
        Cursor cursor = db.rawQuery(query, null);
        boolean updated = false;
        if (cursor.moveToFirst()) {
            String lastUpdate = cursor.getString(0);
            updated = lastUpdate.equals(getCurrentDate());
        }
        cursor.close();
        db.close();
        return updated;
    }

    private void saveRatesToDatabase(List<ExchangeRateItem> rates) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            for (ExchangeRateItem rate : rates) {
                ContentValues values = new ContentValues();
                values.put("currency_name", rate.getCurrencyName());
                values.put("exchange_rate", rate.getExchangeRate());
                values.put("update_date", getCurrentDate());
                db.insert("exchange_rates", null, values);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    private List<ExchangeRateItem> getExchangeRatesFromDatabase() {
        List<ExchangeRateItem> rates = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String query = "SELECT * FROM exchange_rates";
        Cursor cursor = db.rawQuery(query, null);
        int currencyIndex = cursor.getColumnIndex("currency_name");
        int rateIndex = cursor.getColumnIndex("exchange_rate");

        while (cursor.moveToNext()) {
            if (currencyIndex >= 0 && rateIndex >= 0) {
                String currency = cursor.getString(currencyIndex);
                double rate = cursor.getDouble(rateIndex);
                rates.add(new ExchangeRateItem(currency, rate));
            }
        }
        cursor.close();
        db.close();
        return rates;
    }

    private List<ExchangeRateItem> fetchExchangeRatesFromNetwork() {
        // 模拟网络请求，实际应用中应替换为真实API调用
        List<ExchangeRateItem> rates = new ArrayList<>();
        rates.add(new ExchangeRateItem("USD", 6.95));
        rates.add(new ExchangeRateItem("EUR", 7.82));
        rates.add(new ExchangeRateItem("JPY", 0.051));
        return rates;
    }

    private String getCurrentDate() {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
        return sdf.format(new Date());
    }
}